package com.example.blog;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.Test;
import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtilsTest {
    //设置过期时间1小时
    private static final long JWT_EXPIRATION = 60 * 60 * 1000;
    //密钥  长度有要求
    private static final String secretStr = "CIw6DzttvHA+XnrTa2B1EMhLoai1R0vC6jr0Q6y/qsU=";
    //生成 key
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));

    @Test
    public void genJwt() {
        Map<String,Object> claim = new HashMap<>();
        claim.put("id", 1);
        claim.put("name","zhangsan");
        String token = Jwts.builder()
                .setClaims(claim) //自定义内容(负载)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))   //设置过期时间
                .signWith(key) //设置签名
                .compact();

        //将生成的 token 打印出来
        System.out.println(token);
    }

    //生成密钥
    @Test
    public void genKey() {
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String str = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(str);
    }

    @Test
    public void parseToken() {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6MSwiZXhwIjoxNzIzMTk2MTc0fQ.gaKpbMxpGdyx-0mWXQPwNzZAi3Rd2D-VcNC90pWwUPU";
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = build.parseClaimsJws(token).getBody();
        System.out.println(claims);
    }
}
